﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.GangLeaderNeedsWeaponsIssueQuestBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Conversation.Persuasion;
using TaleWorlds.CampaignSystem.Encounters;
using TaleWorlds.CampaignSystem.GameMenus;
using TaleWorlds.CampaignSystem.GameState;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Party.PartyComponents;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class GangLeaderNeedsWeaponsIssueQuestBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency GangLeaderNeedsWeaponsIssueFrequency = IssueBase.IssueFrequency.Common;
    private int _createdPartyCount;
    private static WeaponClass[] _canBeRequestedWeaponClassList = new WeaponClass[1]
    {
      WeaponClass.OneHandedAxe
    };

    private static int CreatedPartyCount
    {
      get
      {
        return Campaign.Current.GetCampaignBehavior<GangLeaderNeedsWeaponsIssueQuestBehavior>()._createdPartyCount;
      }
    }

    public GangLeaderNeedsWeaponsIssueQuestBehavior() => this._createdPartyCount = 0;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
      dataStore.SyncData<int>("_createdPartyCount", ref this._createdPartyCount);
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue), IssueBase.IssueFrequency.Common));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue), IssueBase.IssueFrequency.Common));
    }

    private bool ConditionsHold(Hero IssueOwner)
    {
      return IssueOwner.IsGangLeader && IssueOwner.CurrentSettlement != null && IssueOwner.CurrentSettlement.IsTown && (double) IssueOwner.CurrentSettlement.Town.Loyalty < 60.0;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      ++this._createdPartyCount;
      return (IssueBase) new GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue(issueOwner);
    }

    private static TextObject GetNeededClassTextObject(WeaponClass requestedWeaponClass)
    {
      return requestedWeaponClass == WeaponClass.OneHandedAxe ? new TextObject("{=tza4micZ}one-handed axes") : new TextObject("{=!}Undefined!");
    }

    public class GangLeaderNeedsWeaponsIssue : IssueBase
    {
      private const int BaseNeededWeaponCount = 3;
      private const int BaseRewardGold = 500;
      private const int AlternativeSolutionTroopTierRequirement = 2;
      private const int RequiredSkillLevelForSendingComp = 120;
      private const int IssueDuration = 15;
      private const int QuestTimeLimit = 25;
      [SaveableField(20)]
      private int _requiredWeaponClassIndex;
      [SaveableField(30)]
      private int _averagePriceForItem;

      internal static void AutoGeneratedStaticCollectObjectsGangLeaderNeedsWeaponsIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      internal static object AutoGeneratedGetMemberValue_requiredWeaponClassIndex(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue) o)._requiredWeaponClassIndex;
      }

      internal static object AutoGeneratedGetMemberValue_averagePriceForItem(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue) o)._averagePriceForItem;
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get => IssueBase.AlternativeSolutionScaleFlag.Duration;
      }

      private int RequestedWeaponAmount
      {
        get
        {
          float num = (double) this.IssueDifficultyMultiplier < 0.10000000149011612 || (double) this.IssueDifficultyMultiplier >= 0.30000001192092896 ? ((double) this.IssueDifficultyMultiplier < 0.30000001192092896 || (double) this.IssueDifficultyMultiplier >= 0.60000002384185791 ? 0.3f : 0.2f) : 0.1f;
          return 3 + this._averagePriceForItem == 0 ? 0 : (int) ((double) (20000 / this._averagePriceForItem) * (double) num);
        }
      }

      private int CompanionGoldNeedForAlternativeSolution
      {
        get => this.RewardGold / 2 + this._averagePriceForItem * this.RequestedWeaponAmount / 4;
      }

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 2 + MathF.Ceiling(4f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 7 + MathF.Ceiling(8f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold
      {
        get => 500 + this._averagePriceForItem * this.RequestedWeaponAmount;
      }

      private WeaponClass RequestedWeaponClass
      {
        get
        {
          return GangLeaderNeedsWeaponsIssueQuestBehavior._canBeRequestedWeaponClassList[this._requiredWeaponClassIndex];
        }
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=m24bXmOD}Yes, you can help me. Do you want to make some easy money? I need some 'tools' for my private business. Are you interested?[if:convo_bored][ib:confident2]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=PFNXodyo}What sort of tools?");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=xBaL3RM4}Well, as you know we're not farmers or artisans. I need {NEEDED_AMOUNT} {.%}{NEEDED_TYPE}{.%}. Don't mind the quality, just buy the weapons. Bring them to me and {REWARD_GOLD}{GOLD_ICON} is yours. Got it?[if:convo_bored]");
          explanationByIssueGiver.SetTextVariable("NEEDED_AMOUNT", this.RequestedWeaponAmount);
          explanationByIssueGiver.SetTextVariable("REWARD_GOLD", this.RewardGold);
          explanationByIssueGiver.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          explanationByIssueGiver.SetTextVariable("NEEDED_TYPE", GangLeaderNeedsWeaponsIssueQuestBehavior.GetNeededClassTextObject(this.RequestedWeaponClass));
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=0i8RgslK}Or, maybe one of your trusted companions can buy the {ITEM_TYPE}. I reckon they'll cost {COMPANION_NEED_GOLD_AMOUNT}{GOLD_ICON} denars, and they'd best take at least {ALTERNATIVE_TROOP_AMOUNT} men for protection.[if:convo_bored]");
          explanationByIssueGiver.SetTextVariable("COMPANION_NEED_GOLD_AMOUNT", this.CompanionGoldNeedForAlternativeSolution);
          explanationByIssueGiver.SetTextVariable("ITEM_TYPE", GangLeaderNeedsWeaponsIssueQuestBehavior.GetNeededClassTextObject(this.RequestedWeaponClass));
          explanationByIssueGiver.SetTextVariable("ALTERNATIVE_TROOP_AMOUNT", this.GetTotalAlternativeSolutionNeededMenCount());
          explanationByIssueGiver.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          TextObject solutionAcceptByPlayer = new TextObject("{=ABYGws1M}I'll bring you {NEEDED_AMOUNT} of those by myself.");
          solutionAcceptByPlayer.SetTextVariable("NEEDED_AMOUNT", this.RequestedWeaponAmount);
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get
        {
          return new TextObject("{=Ggjb9BVQ}Actually I prefer not to get involved in this kind of business personally but my men will help you out.");
        }
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          return new TextObject("{=HawJormK}That's fine, so long as your men know well enough to handle this quietly. Good luck.");
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=aG9iX1a8}We're looking forward to trying out our new \"tools\" on some bastard's head. Let your boys know that drinks are on us when they get here.");
        }
      }

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=otwfa0K3}{QUEST_GIVER.LINK}, a gang leader from {SETTLEMENT} wanted you to buy some weapons for {?QUEST_GIVER.GENDER}her{?}his{\\?} private business. {?QUEST_GIVER.GENDER}She{?}He{\\?} offers you {REWARD_GOLD}{GOLD_ICON} on their delivery. You asked {COMPANION.LINK} to take some of your men and buy {NEEDED_AMOUNT} units of {NEEDED_TYPE} to deliver to {QUEST_GIVER.LINK} in {SETTLEMENT}. They should rejoin your party in {RETURN_DAYS} days.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject, parent);
          parent.SetTextVariable("SETTLEMENT", this.IssueOwner.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          parent.SetTextVariable("NEEDED_AMOUNT", this.RequestedWeaponAmount);
          parent.SetTextVariable("NEEDED_TYPE", GangLeaderNeedsWeaponsIssueQuestBehavior.GetNeededClassTextObject(this.RequestedWeaponClass));
          parent.SetTextVariable("REWARD_GOLD", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      public override bool IsThereAlternativeSolution => true;

      public override bool IsThereLordSolution => false;

      public override TextObject Title => new TextObject("{=zKHkS5Gf}Gang leader needs weapons");

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=VYq93e36}A gang leader needs you to buy weapons for {?QUEST_GIVER.GENDER}her{?}his{\\?} men.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public GangLeaderNeedsWeaponsIssue(Hero issueOwner)
        : base(issueOwner, CampaignTime.DaysFromNow(15f))
      {
        MBList<(WeaponClass, int)> e = new MBList<(WeaponClass, int)>();
        foreach (WeaponClass requestedWeaponClass in GangLeaderNeedsWeaponsIssueQuestBehavior._canBeRequestedWeaponClassList)
        {
          int priceForWeaponClass = this.CalculateAveragePriceForWeaponClass(requestedWeaponClass);
          if (priceForWeaponClass > 0)
            e.Add((requestedWeaponClass, priceForWeaponClass));
        }
        (WeaponClass, int) selectedItemAndPrize = e.GetRandomElement<(WeaponClass, int)>();
        this._averagePriceForItem = selectedItemAndPrize.Item2;
        this._requiredWeaponClassIndex = Array.FindIndex<WeaponClass>(GangLeaderNeedsWeaponsIssueQuestBehavior._canBeRequestedWeaponClassList, (Predicate<WeaponClass>) (x => x == selectedItemAndPrize.Item1));
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        if (issueEffect == DefaultIssueEffects.SettlementSecurity)
          return 1f;
        return issueEffect == DefaultIssueEffects.IssueOwnerPower ? -0.2f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Trade) >= hero.GetSkillValue(DefaultSkills.Crafting) ? DefaultSkills.Trade : DefaultSkills.Crafting, 120);
      }

      private int CalculateAveragePriceForWeaponClass(WeaponClass weaponClass)
      {
        int num1 = 0;
        int num2 = 0;
        foreach (Settlement settlement in (List<Settlement>) Settlement.All)
        {
          if (settlement.IsTown)
          {
            for (int index = 0; index < settlement.ItemRoster.Count; ++index)
            {
              ItemRosterElement itemRosterElement = settlement.ItemRoster[index];
              WeaponComponent weaponComponent = itemRosterElement.EquipmentElement.Item.WeaponComponent;
              if ((weaponComponent != null ? (weaponComponent.PrimaryWeapon.WeaponClass == weaponClass ? 1 : 0) : 0) != 0)
              {
                num2 += itemRosterElement.Amount;
                num1 += itemRosterElement.EquipmentElement.ItemValue;
              }
            }
          }
        }
        return num1 / (num2 == 0 ? 1 : num2);
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (800.0 + 900.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2) && QuestHelper.CheckGoldForAlternativeSolution(this.CompanionGoldNeedForAlternativeSolution, ref explanation);
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool IsTroopTypeNeededByAlternativeSolution(CharacterObject character)
      {
        return character.Tier >= 2;
      }

      public override void AlternativeSolutionStartConsequence()
      {
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, (Hero) null, this.CompanionGoldNeedForAlternativeSolution);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        ChangeCrimeRatingAction.Apply(this.IssueOwner.CurrentSettlement.MapFaction, 10f);
        this.IssueOwner.AddPower(10f);
        this.RelationshipChangeWithIssueOwner = 5;
        this.IssueOwner.CurrentSettlement.Town.Security -= 30f;
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Common;

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        flag = IssueBase.PreconditionFlags.None;
        skill = (SkillObject) null;
        relationHero = (Hero) null;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flag |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (this.IssueOwner.CurrentSettlement.OwnerClan == Clan.PlayerClan)
          flag |= IssueBase.PreconditionFlags.PlayerIsOwnerOfSettlement;
        return flag == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        return this.IssueOwner.CurrentSettlement?.Town != null && this.IssueOwner.CurrentSettlement.OwnerClan != Clan.PlayerClan && (double) this.IssueOwner.CurrentSettlement.Town.Loyalty < 75.0;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(25f), this.RewardGold, this._requiredWeaponClassIndex, this.RequestedWeaponAmount, this.IssueDifficultyMultiplier, this._averagePriceForItem);
      }
    }

    public class GangLeaderNeedsWeaponsIssueQuest : QuestBase
    {
      private const int LowCrimeRatingValue = 30;
      private const int HighCrimeRatingValue = 60;
      private WeaponClass _requestedWeaponClass;
      [SaveableField(10)]
      private int _randomForRequiredWeaponClass;
      [SaveableField(20)]
      private int _requestedWeaponAmount;
      [SaveableField(30)]
      private bool _playerDodgedGuards;
      [SaveableField(40)]
      private int _collectedItemAmount;
      [SaveableField(50)]
      private bool _lowCrimeRatingWillBeApplied;
      [SaveableField(60)]
      private bool _highCrimeRatingWillBeApplied;
      [SaveableField(71)]
      private Dictionary<EquipmentElement, int> _weaponsThatGuardTook;
      [SaveableField(80)]
      private float _issueDifficulty;
      [SaveableField(90)]
      private float _rewardGold;
      [SaveableField(100)]
      private int _bribeGold;
      [SaveableField(101)]
      private bool _persuasionTriedOnce;
      private bool _checkForBattleResult;
      private MobileParty _guardsParty;
      private bool _startBattleMission;
      private bool _playerGoBack;
      private PersuasionTask _task;
      private const PersuasionDifficulty Difficulty = PersuasionDifficulty.VeryHard;
      [SaveableField(110)]
      private JournalLog _playerStartsQuestLog;

      internal static void AutoGeneratedStaticCollectObjectsGangLeaderNeedsWeaponsIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._weaponsThatGuardTook);
        collectedObjects.Add((object) this._playerStartsQuestLog);
      }

      internal static object AutoGeneratedGetMemberValue_randomForRequiredWeaponClass(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._randomForRequiredWeaponClass;
      }

      internal static object AutoGeneratedGetMemberValue_requestedWeaponAmount(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._requestedWeaponAmount;
      }

      internal static object AutoGeneratedGetMemberValue_playerDodgedGuards(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._playerDodgedGuards;
      }

      internal static object AutoGeneratedGetMemberValue_collectedItemAmount(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._collectedItemAmount;
      }

      internal static object AutoGeneratedGetMemberValue_lowCrimeRatingWillBeApplied(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._lowCrimeRatingWillBeApplied;
      }

      internal static object AutoGeneratedGetMemberValue_highCrimeRatingWillBeApplied(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._highCrimeRatingWillBeApplied;
      }

      internal static object AutoGeneratedGetMemberValue_weaponsThatGuardTook(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._weaponsThatGuardTook;
      }

      internal static object AutoGeneratedGetMemberValue_issueDifficulty(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._issueDifficulty;
      }

      internal static object AutoGeneratedGetMemberValue_rewardGold(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._rewardGold;
      }

      internal static object AutoGeneratedGetMemberValue_bribeGold(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._bribeGold;
      }

      internal static object AutoGeneratedGetMemberValue_persuasionTriedOnce(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._persuasionTriedOnce;
      }

      internal static object AutoGeneratedGetMemberValue_playerStartsQuestLog(object o)
      {
        return (object) ((GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest) o)._playerStartsQuestLog;
      }

      public override TextObject Title => new TextObject("{=zKHkS5Gf}Gang leader needs weapons");

      public override bool IsRemainingTimeHidden => false;

      private TextObject PlayerStartsQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=B3WyJjBx}{QUEST_GIVER.LINK}, a gang leader from {SETTLEMENT}, asked you to buy some weapons for {?QUEST_GIVER.GENDER}her{?}his{\\?} private business. {?QUEST_GIVER.GENDER}She{?}He{\\?} offered you {REWARD_GOLD}{GOLD_ICON} for their delivery. {?QUEST_GIVER.GENDER}She{?}He{\\?} asked you to buy {NEEDED_AMOUNT} {NEEDED_TYPE} and deliver them to {SETTLEMENT} where {QUEST_GIVER.LINK}'s men will be waiting for you. {?QUEST_GIVER.GENDER}She{?}He{\\?} promised to give you {REWARD_GOLD}{GOLD_ICON} for your troubles.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("SETTLEMENT", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          parent.SetTextVariable("NEEDED_AMOUNT", this._requestedWeaponAmount);
          parent.SetTextVariable("NEEDED_TYPE", GangLeaderNeedsWeaponsIssueQuestBehavior.GetNeededClassTextObject(this._requestedWeaponClass));
          parent.SetTextVariable("REWARD_GOLD", this._rewardGold);
          GameTexts.SetVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject SuccessQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=R6V2Jv3a}You have delivered the weapons to the {QUEST_GIVER.LINK} as promised.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject FailPlayerDefeatedAgainstGuardsLogText
      {
        get
        {
          TextObject parent = new TextObject("{=XrxCaoT2}You have failed to deliver the weapons to the {QUEST_GIVER.LINK}.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject FailQuestTimedOutLogText
      {
        get
        {
          TextObject parent = new TextObject("{=4n71Xoyq}You have failed to bring the weapons to the {QUEST_GIVER.LINK} in time.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject OwnerOfQuestSettlementIsPlayerClanLogText
      {
        get
        {
          TextObject parent = new TextObject("{=Txtwv90o}Your clan has conquered the town into which you are trying to smuggle weapons. As the {?PLAYER.GENDER}lady{?}lord{\\?} of the town you cannot get involved in this kind of activity. Your agreement with the {QUEST_GIVER.LINK} has canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          return parent;
        }
      }

      public GangLeaderNeedsWeaponsIssueQuest(
        string questId,
        Hero questGiver,
        CampaignTime dueTime,
        int rewardGold,
        int randomForRequiredWeaponClass,
        int requestedWeaponAmount,
        float issueDifficulty,
        int averagePrice)
        : base(questId, questGiver, dueTime, rewardGold)
      {
        this._randomForRequiredWeaponClass = randomForRequiredWeaponClass;
        this._requestedWeaponClass = GangLeaderNeedsWeaponsIssueQuestBehavior._canBeRequestedWeaponClassList[this._randomForRequiredWeaponClass];
        this._requestedWeaponAmount = requestedWeaponAmount;
        this._weaponsThatGuardTook = new Dictionary<EquipmentElement, int>();
        this._issueDifficulty = issueDifficulty;
        this._rewardGold = (float) rewardGold;
        this._bribeGold = averagePrice * requestedWeaponAmount / 4;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad()
      {
        this.SetDialogs();
        this._requestedWeaponClass = GangLeaderNeedsWeaponsIssueQuestBehavior._canBeRequestedWeaponClassList[this._randomForRequiredWeaponClass];
      }

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.SettlementEntered.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement, Hero>(this.OnSettlementEnter));
        CampaignEvents.OnSettlementLeftEvent.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement>(this.OnSettlementLeft));
        CampaignEvents.PlayerInventoryExchangeEvent.AddNonSerializedListener((object) this, new Action<List<(ItemRosterElement, int)>, List<(ItemRosterElement, int)>, bool>(this.OnPlayerInventoryChanged));
        CampaignEvents.OnNewItemCraftedEvent.AddNonSerializedListener((object) this, new Action<ItemObject, ItemModifier, bool>(this.OnItemCrafted));
        CampaignEvents.GameMenuOpened.AddNonSerializedListener((object) this, new Action<MenuCallbackArgs>(this.OnGameMenuOpened));
        CampaignEvents.OnSettlementOwnerChangedEvent.AddNonSerializedListener((object) this, new Action<Settlement, bool, Hero, Hero, Hero, ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail>(this.OnSettlementOwnerChanged));
        CampaignEvents.OnEquipmentSmeltedByHeroEvent.AddNonSerializedListener((object) this, new Action<Hero, EquipmentElement>(this.OnEquipmentSmeltedByHero));
      }

      protected override void OnBeforeTimedOut(
        ref bool completeWithSuccess,
        ref bool doNotResolveTheQuest)
      {
        this.GiveBackPlayersWeaponsOnCancelOrTimeOut();
      }

      public override void OnCanceled() => this.GiveBackPlayersWeaponsOnCancelOrTimeOut();

      private void GiveBackPlayersWeaponsOnCancelOrTimeOut()
      {
        if (this._weaponsThatGuardTook.Count <= 0)
          return;
        foreach (KeyValuePair<EquipmentElement, int> keyValuePair in this._weaponsThatGuardTook)
          PartyBase.MainParty.ItemRoster.AddToCounts(keyValuePair.Key, keyValuePair.Value);
      }

      private void OnEquipmentSmeltedByHero(Hero hero, EquipmentElement equipmentElement)
      {
        if (hero.PartyBelongedTo != MobileParty.MainParty)
          return;
        ItemObject itemObject = equipmentElement.Item;
        if (itemObject.WeaponComponent == null || itemObject.WeaponComponent.PrimaryWeapon.WeaponClass != this._requestedWeaponClass)
          return;
        this.SetCurrentItemAmount(this._collectedItemAmount - 1);
      }

      private void OnItemCrafted(
        ItemObject itemObject,
        ItemModifier overriddenItemModifier,
        bool isCraftingOrderItem)
      {
        if (isCraftingOrderItem || itemObject.WeaponComponent == null || itemObject.WeaponComponent.PrimaryWeapon.WeaponClass != this._requestedWeaponClass)
          return;
        this.SetCurrentItemAmount(this._collectedItemAmount + 1);
      }

      private void SetCurrentItemAmount(int value)
      {
        this._collectedItemAmount = value;
        this._playerStartsQuestLog?.UpdateCurrentProgress(this._collectedItemAmount);
      }

      private void OnSettlementOwnerChanged(
        Settlement settlement,
        bool openToClaim,
        Hero newOwner,
        Hero oldOwner,
        Hero capturerHero,
        ChangeOwnerOfSettlementAction.ChangeOwnerOfSettlementDetail detail)
      {
        if (settlement != this.QuestGiver.CurrentSettlement || newOwner != Hero.MainHero)
          return;
        this.AddLog(this.OwnerOfQuestSettlementIsPlayerClanLogText);
        this.CompleteQuestWithCancel();
      }

      private void OnGameMenuOpened(MenuCallbackArgs args)
      {
        if (!(args.MenuContext.GameMenu.StringId == "town") || Campaign.Current.GameMenuManager.NextLocation != null || !(GameStateManager.Current.ActiveState is MapState))
          return;
        if (this._checkForBattleResult && PlayerEncounter.Battle != null && PlayerEncounter.Battle.InvolvedParties.Any<PartyBase>((Func<PartyBase, bool>) (x => x == this._guardsParty.Party)))
        {
          int num = PlayerEncounter.Battle.WinningSide == PlayerEncounter.Battle.PlayerSide ? 1 : 0;
          this._checkForBattleResult = false;
          PlayerEncounter.Finish();
          if (num != 0)
            this.PlayerDodgedGuards();
          else
            this.PlayerDefeatedAgainstGuards();
        }
        if (this._startBattleMission)
        {
          this._startBattleMission = false;
          this.StartFight();
        }
        if (!this._playerGoBack)
          return;
        PlayerEncounter.LeaveEncounter = true;
        PlayerEncounter.Finish();
        this._playerGoBack = false;
      }

      private void OnPlayerInventoryChanged(
        List<(ItemRosterElement, int)> purchasedItems,
        List<(ItemRosterElement, int)> soldItems,
        bool isTrading)
      {
        this.CalculateAndSetRequestedItemCountOnPlayer();
      }

      private void OnSettlementLeft(MobileParty party, Settlement settlement)
      {
        if (settlement != this.QuestGiver.CurrentSettlement || party != MobileParty.MainParty)
          return;
        if (this._weaponsThatGuardTook.Count > 0)
        {
          int num1 = 1500;
          bool flag = false;
          foreach (KeyValuePair<EquipmentElement, int> keyValuePair in this._weaponsThatGuardTook.OrderBy<KeyValuePair<EquipmentElement, int>, int>((Func<KeyValuePair<EquipmentElement, int>, int>) (x => x.Key.Item.Value)).ToList<KeyValuePair<EquipmentElement, int>>())
          {
            int num2 = 0;
            for (int index = 0; index < keyValuePair.Value && num1 > 0; ++index)
            {
              if ((double) MBRandom.RandomFloat >= 0.6)
              {
                ++num2;
                num1 -= keyValuePair.Key.Item.Value;
                flag = true;
              }
            }
            if (keyValuePair.Value > num2)
              PartyBase.MainParty.ItemRoster.AddToCounts(keyValuePair.Key, keyValuePair.Value - num2);
          }
          if (flag)
            MBInformationManager.AddQuickInformation(new TextObject("{=Ibm1A68t}The guards gave your weapons back to you but you noticed something missing."));
          else
            MBInformationManager.AddQuickInformation(new TextObject("{=isGIZ18i}The guards gave all your weapons back to you."));
          this._weaponsThatGuardTook.Clear();
          this.CalculateAndSetRequestedItemCountOnPlayer();
        }
        if (this._guardsParty == null)
          return;
        EnterSettlementAction.ApplyForParty(this._guardsParty, this.QuestGiver.CurrentSettlement);
        this._guardsParty.IsVisible = false;
        this._guardsParty.IsActive = false;
      }

      private void OnSettlementEnter(MobileParty party, Settlement settlement, Hero hero)
      {
        if (this._playerDodgedGuards || party != MobileParty.MainParty || settlement != this.QuestGiver.CurrentSettlement || MobileParty.MainParty.Army != null || Campaign.Current.GameMenuManager.NextLocation != null || !(GameStateManager.Current.ActiveState is MapState) || PlayerEncounter.EncounterSettlement == null)
          return;
        this.CalculateAndSetRequestedItemCountOnPlayer();
        if (this._collectedItemAmount < this._requestedWeaponAmount / 3 || this._playerGoBack)
          return;
        if (this._guardsParty == null)
          this.CreateGuardsParty();
        CampaignMapConversation.OpenConversation(new ConversationCharacterData(CharacterObject.PlayerCharacter, PartyBase.MainParty), new ConversationCharacterData(ConversationHelper.GetConversationCharacterPartyLeader(this._guardsParty.Party), isCivilianEquipmentRequiredForLeader: true));
      }

      private void CreateGuardsParty()
      {
        this._guardsParty = MobileParty.CreateParty("weapon_smuggling_quest_guards_party_" + (object) GangLeaderNeedsWeaponsIssueQuestBehavior.CreatedPartyCount, (PartyComponent) null);
        TextObject name = new TextObject("{=7aaAWc01}Guard's Party");
        this._guardsParty.InitializeMobilePartyAtPosition(new TroopRoster(this._guardsParty.Party), new TroopRoster(this._guardsParty.Party), this.QuestGiver.CurrentSettlement.GatePosition);
        this._guardsParty.SetCustomName(name);
        this._guardsParty.SetCustomHomeSettlement(this.QuestGiver.CurrentSettlement);
        this._guardsParty.Party.SetCustomOwner(this.QuestGiver.CurrentSettlement.OwnerClan.Leader);
        this._guardsParty.MemberRoster.AddToCounts(CharacterObject.All.First<CharacterObject>((Func<CharacterObject, bool>) (x => x.StringId == "guard_" + this._guardsParty.HomeSettlement.Culture.StringId)), 1, true);
        this._guardsParty.SetPartyUsedByQuest(true);
        this._guardsParty.Ai.DisableAi();
        this._guardsParty.MemberRoster.AddToCounts(this._guardsParty.HomeSettlement.Culture.MeleeMilitiaTroop, (int) (float) (5.0 + 15.0 * (double) this._issueDifficulty));
        EnterSettlementAction.ApplyForParty(this._guardsParty, this.QuestGiver.CurrentSettlement);
        this._guardsParty.IsVisible = false;
        this._guardsParty.ActualClan = this.QuestGiver.CurrentSettlement.OwnerClan;
      }

      protected override void SetDialogs()
      {
        Campaign.Current.ConversationManager.AddDialogFlow(this.GetGuardDialogFlow(), (object) this);
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=nQoAsBZY}When you enter the town my men will take the weapons from you. Good luck.")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=CQH7E6Gr}What about my weapons?[if:convo_confused_normal][ib:hip]")).Condition((ConversationSentence.OnConditionDelegate) (() => Hero.OneToOneConversationHero == this.QuestGiver)).BeginPlayerOptions().PlayerOption(new TextObject("{=RbToDs0n}Here is your cargo. Now it's time for payment.")).Condition(new ConversationSentence.OnConditionDelegate(this.CheckIfPlayerHasEnoughRequestedWeapons)).NpcLine(new TextObject("{=nixINYwE}Yes of course. It was a pleasure doing business with you.[if:convo_mocking_aristocratic]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => Campaign.Current.ConversationManager.ConversationEndOneShot += new Action(this.PlayerSuccessfullyDeliveredWeapons))).CloseDialog().PlayerOption(new TextObject("{=bj49Bq15}It's not that easy to find what you wanted. Be patient, please.")).NpcLine(new TextObject("{=avFXbBLV}I know how it is. Just bring me the weapons.[if:convo_bored2]")).EndPlayerOptions().CloseDialog();
      }

      private bool CheckIfPlayerHasEnoughRequestedWeapons()
      {
        this.CalculateAndSetRequestedItemCountOnPlayer();
        return this._collectedItemAmount >= this._requestedWeaponAmount;
      }

      private void CalculateAndSetRequestedItemCountOnPlayer()
      {
        int num = 0;
        foreach (ItemRosterElement itemRosterElement in PartyBase.MainParty.ItemRoster)
        {
          EquipmentElement equipmentElement = itemRosterElement.EquipmentElement;
          if (equipmentElement.Item != null)
          {
            equipmentElement = itemRosterElement.EquipmentElement;
            if (equipmentElement.Item.WeaponComponent != null)
            {
              equipmentElement = itemRosterElement.EquipmentElement;
              if (equipmentElement.Item.WeaponComponent.PrimaryWeapon.WeaponClass == this._requestedWeaponClass)
                num += itemRosterElement.Amount;
            }
          }
        }
        this.SetCurrentItemAmount(num);
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this._playerStartsQuestLog = this.AddDiscreteLog(this.PlayerStartsQuestLogText, new TextObject("{=9j7LJk60}Collected Items"), this._collectedItemAmount, this._requestedWeaponAmount);
        this.CalculateAndSetRequestedItemCountOnPlayer();
      }

      private DialogFlow GetGuardDialogFlow()
      {
        TextObject npcText1 = new TextObject("{=wBBidWVw}What have we here? You can't enter the town with so many weapons. Hand them over! You can retrieve them when you leave.[if:convo_thinking][closed2]");
        TextObject text1 = new TextObject("{=oVAtPtsu}Clear the way! We don't want to use force!");
        TextObject text2 = new TextObject("{=JL204Kc0}Sure... sure. We'll hand them over..");
        TextObject text3 = new TextObject("{=nlCa3tW8}You seem like a reasonable man. What is your price?");
        TextObject text4 = new TextObject("{=VUjaLmIH}Relax. We have permission. Let us pass. ");
        TextObject text5 = new TextObject("{=tGFgar0U}Fine. We won't enter at all, then. Good bye.");
        TextObject npcText2 = new TextObject("{=Qb7N6txQ}Mmm. For {BRIBE_COST}{GOLD_ICON} denars, I could be persuaded that this is just harmless scrap metal...[if:convo_mocking_aristocratic][ib:confident]");
        npcText2.SetTextVariable("BRIBE_COST", this._bribeGold);
        npcText2.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
        DialogFlow dialog = DialogFlow.CreateDialogFlow("start", 125).NpcLine(npcText1).Condition(new ConversationSentence.OnConditionDelegate(this.DialogStartCondition)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this._task = this.GetPersuasionTask())).BeginPlayerOptions().PlayerOption(text1).ClickableCondition(new ConversationSentence.OnClickableConditionDelegate(this.CheckPlayerHealth)).BeginNpcOptions().NpcOption(new TextObject("{=NcQZz4N2}This is my last warning! It would be better for both sides if you don't resist.[if:convo_grave][ib:closed]"), new ConversationSentence.OnConditionDelegate(this.CheckPlayersPartySize)).BeginPlayerOptions().PlayerOption(new TextObject("{=NTlbbrwB}If there will be a fight, then we will fight")).NpcLine(new TextObject("{=h5np5kcC}All right, all right... We don't want any trouble here, okay? Go on.[if:convo_contemptuous]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.PlayerDodgeGuardsLowCrimeRating)).CloseDialog().PlayerOption(new TextObject("{=pfxG5Ubu}Fine, fine. Take our weapons.")).NpcLine(new TextObject("{=A8lvIDVw}Wise decision! Now move along![if:convo_angry] ")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeleteAllWeaponsFromPlayer)).CloseDialog().EndPlayerOptions().NpcOption(new TextObject("{=G632MneX}This is my last warning! Hand over your weapons![if:convo_thinking][ib:closed]"), (ConversationSentence.OnConditionDelegate) null).BeginPlayerOptions().PlayerOption(new TextObject("{=NTlbbrwB}If there will be a fight, then we will fight")).NpcLine(new TextObject("{=8WaoQpYn}Oh there will be one, all right.[if:convo_predatory][ib:warrior]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this._startBattleMission = true)).CloseDialog().PlayerOption(new TextObject("{=pfxG5Ubu}Fine, fine. Take our weapons.")).NpcLine(new TextObject("{=3xyd2Dxu}Good. That saves us all trouble.[if:convo_grave][ib:warrior2]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeleteAllWeaponsFromPlayer)).CloseDialog().EndPlayerOptions().EndNpcOptions().PlayerOption(text2).NpcLine(new TextObject("{=GyI86plp}Don't worry. I guarantee your property will be returned, if everything's in order like you say...[if:convo_calm_friendly][ib:closed]")).Consequence(new ConversationSentence.OnConsequenceDelegate(this.DeleteAllWeaponsFromPlayer)).CloseDialog().PlayerOption(text3).NpcLine(npcText2).BeginPlayerOptions().PlayerOption(new TextObject("{=Obk7j3ai}Here it is. Now let us pass")).ClickableCondition(new ConversationSentence.OnClickableConditionDelegate(this.HasPlayerEnoughMoneyToBribe)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.PlayerBribeGuard)).NpcLine(new TextObject("{=musbt5Hm}Sorry for the interruption. Go on please...[if:convo_bored2]")).CloseDialog().PlayerOption(new TextObject("{=d5ztuP3P}That's too much.")).NpcLine(new TextObject("{=49IwOe5E}As you wish...[if:convo_normal]")).GotoDialogState("start").EndPlayerOptions().PlayerOption(text4).Condition((ConversationSentence.OnConditionDelegate) (() => !this._persuasionTriedOnce)).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this._persuasionTriedOnce = true)).GotoDialogState("start_guard_persuasion").PlayerOption(text5).NpcLine(new TextObject("{=xvYDbEUa}All right. Go on.[if:convo_bored]")).Consequence((ConversationSentence.OnConsequenceDelegate) (() => this._playerGoBack = true)).CloseDialog().EndPlayerOptions();
        this.AddPersuasionDialogs(dialog);
        return dialog;
      }

      private bool CheckPlayerHealth(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        if (!Hero.MainHero.IsWounded)
          return true;
        explanation = new TextObject("{=yNMrF2QF}You are wounded");
        return false;
      }

      private void AddPersuasionDialogs(DialogFlow dialog)
      {
        dialog.AddDialogLine("guard_persuation_weapon_smuggling_check_accepted", "start_guard_persuasion", "guard_persuation_weapon_smuggling_start_reservation", "{=v5tPWFFu}Then, what is the purpose of this?", new ConversationSentence.OnConditionDelegate(this.persuasion_start_with_guards_on_condition), new ConversationSentence.OnConsequenceDelegate(this.persuasion_start_with_guards_on_consequence), (object) this);
        dialog.AddDialogLine("guard_persuation_weapon_smuggling_rejected", "guard_persuation_weapon_smuggling_start_reservation", "start", "{=!}{FAILED_PERSUASION_LINE}", new ConversationSentence.OnConditionDelegate(this.persuasion_failed_with_guards_on_condition), new ConversationSentence.OnConsequenceDelegate(this.persuasion_rejected_with_guards_on_consequence), (object) this);
        dialog.AddDialogLine("guard_persuation_weapon_smuggling_attempt", "guard_persuation_weapon_smuggling_start_reservation", "guard_persuation_weapon_smuggling_select_option", "{=D9SS2Oh0}I'm going to need you to tell me a little more.", (ConversationSentence.OnConditionDelegate) (() => !this.persuasion_failed_with_guards_on_condition()), (ConversationSentence.OnConsequenceDelegate) null, (object) this);
        dialog.AddDialogLine("guard_persuation_weapon_smuggling_success", "guard_persuation_weapon_smuggling_start_reservation", "close_window", "{=kD8yLgRv}Go on. But I have my eye on you.", new ConversationSentence.OnConditionDelegate(ConversationManager.GetPersuasionProgressSatisfied), new ConversationSentence.OnConsequenceDelegate(this.persuasion_complete_with_guards_on_consequence), (object) this, 200);
        DialogFlow dialogFlow1 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate1 = new ConversationSentence.OnConditionDelegate(this.guard_persuation_weapon_smuggling_select_option_1_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate1 = new ConversationSentence.OnConsequenceDelegate(this.guard_persuation_weapon_smuggling_select_option_1_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate1 = new ConversationSentence.OnPersuasionOptionDelegate(this.guard_persuation_weapon_smuggling_setup_option_1);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate1 = new ConversationSentence.OnClickableConditionDelegate(this.guard_persuation_weapon_smuggling_clickable_option_1_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate2 = persuasionOptionDelegate1;
        dialogFlow1.AddPlayerLine("guard_persuation_weapon_smuggling_select_option_1", "guard_persuation_weapon_smuggling_select_option", "guard_persuation_weapon_smuggling_selected_option_response", "{=!}{GUARDS_PERSUADE_ATTEMPT_1}", conditionDelegate1, consequenceDelegate1, (object) this, clickableConditionDelegate: clickableConditionDelegate1, persuasionOptionDelegate: persuasionOptionDelegate2);
        DialogFlow dialogFlow2 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate2 = new ConversationSentence.OnConditionDelegate(this.guard_persuation_weapon_smuggling_select_option_2_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate2 = new ConversationSentence.OnConsequenceDelegate(this.guard_persuation_weapon_smuggling_select_option_2_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate3 = new ConversationSentence.OnPersuasionOptionDelegate(this.guard_persuation_weapon_smuggling_setup_option_2);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate2 = new ConversationSentence.OnClickableConditionDelegate(this.guard_persuation_weapon_smuggling_clickable_option_2_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate4 = persuasionOptionDelegate3;
        dialogFlow2.AddPlayerLine("guard_persuation_weapon_smuggling_select_option_2", "guard_persuation_weapon_smuggling_select_option", "guard_persuation_weapon_smuggling_selected_option_response", "{=!}{GUARDS_PERSUADE_ATTEMPT_2}", conditionDelegate2, consequenceDelegate2, (object) this, clickableConditionDelegate: clickableConditionDelegate2, persuasionOptionDelegate: persuasionOptionDelegate4);
        DialogFlow dialogFlow3 = dialog;
        ConversationSentence.OnConditionDelegate conditionDelegate3 = new ConversationSentence.OnConditionDelegate(this.guard_persuation_weapon_smuggling_select_option_3_on_condition);
        ConversationSentence.OnConsequenceDelegate consequenceDelegate3 = new ConversationSentence.OnConsequenceDelegate(this.guard_persuation_weapon_smuggling_select_option_3_on_consequence);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate5 = new ConversationSentence.OnPersuasionOptionDelegate(this.guard_persuation_weapon_smuggling_setup_option_3);
        ConversationSentence.OnClickableConditionDelegate clickableConditionDelegate3 = new ConversationSentence.OnClickableConditionDelegate(this.guard_persuation_weapon_smuggling_clickable_option_3_on_condition);
        ConversationSentence.OnPersuasionOptionDelegate persuasionOptionDelegate6 = persuasionOptionDelegate5;
        dialogFlow3.AddPlayerLine("guard_persuation_weapon_smuggling_select_option_3", "guard_persuation_weapon_smuggling_select_option", "guard_persuation_weapon_smuggling_selected_option_response", "{=!}{GUARDS_PERSUADE_ATTEMPT_3}", conditionDelegate3, consequenceDelegate3, (object) this, clickableConditionDelegate: clickableConditionDelegate3, persuasionOptionDelegate: persuasionOptionDelegate6);
        dialog.AddDialogLine("guard_persuation_weapon_smuggling_select_option_reaction", "guard_persuation_weapon_smuggling_selected_option_response", "guard_persuation_weapon_smuggling_start_reservation", "{=!}{PERSUASION_REACTION}", new ConversationSentence.OnConditionDelegate(this.guard_persuation_weapon_smuggling_selected_option_response_on_condition), new ConversationSentence.OnConsequenceDelegate(this.guard_persuation_weapon_smuggling_selected_option_response_on_consequence), (object) this);
      }

      private void persuasion_start_with_guards_on_consequence()
      {
        ConversationManager.StartPersuasion(2f, 1f, 0.0f, 2f, 2f, 0.0f, PersuasionDifficulty.VeryHard);
      }

      private bool persuasion_start_with_guards_on_condition()
      {
        return this._guardsParty != null && CharacterObject.OneToOneConversationCharacter == ConversationHelper.GetConversationCharacterPartyLeader(this._guardsParty.Party);
      }

      private bool persuasion_failed_with_guards_on_condition()
      {
        if (!this._task.Options.All<PersuasionOptionArgs>((Func<PersuasionOptionArgs, bool>) (x => x.IsBlocked)) || ConversationManager.GetPersuasionProgressSatisfied())
          return false;
        MBTextManager.SetTextVariable("FAILED_PERSUASION_LINE", this._task.FinalFailLine, false);
        return true;
      }

      private void persuasion_rejected_with_guards_on_consequence()
      {
        PlayerEncounter.LeaveEncounter = false;
        ConversationManager.EndPersuasion();
      }

      private void persuasion_complete_with_guards_on_consequence()
      {
        this.PlayerDodgedGuards();
        PlayerEncounter.LeaveEncounter = true;
        ConversationManager.EndPersuasion();
      }

      private PersuasionTask GetPersuasionTask()
      {
        PersuasionTask persuasionTask = new PersuasionTask(0);
        persuasionTask.FinalFailLine = new TextObject("{=XCJGl82o}Do you think you can pull one over on me? Now hand over the weapons![if:convo_furious][ib:aggressive]");
        persuasionTask.TryLaterLine = new TextObject("{=!}TODO");
        persuasionTask.SpokenLine = new TextObject("{=6P1ruzsC}Maybe...");
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Roguery, DefaultTraits.RogueSkills, TraitEffect.Positive, PersuasionArgumentStrength.Hard, false, new TextObject("{=1hbos200}Here are some documents from the chancellery.")));
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Roguery, DefaultTraits.Calculating, TraitEffect.Positive, PersuasionArgumentStrength.Normal, false, new TextObject("{=UHCKXapl}The metalworkers' guild asked for them. Don't worry, they'll be melted into scrap.")));
        persuasionTask.AddOptionToTask(new PersuasionOptionArgs(DefaultSkills.Charm, DefaultTraits.RogueSkills, TraitEffect.Positive, PersuasionArgumentStrength.VeryHard, false, new TextObject("{=8Wa6OxG8}It's secret. You must be new in your post if you don't know who I am and what I do.")));
        return persuasionTask;
      }

      private bool guard_persuation_weapon_smuggling_selected_option_response_on_condition()
      {
        PersuasionOptionResult optionResult = ConversationManager.GetPersuasionChosenOptions().Last<Tuple<PersuasionOptionArgs, PersuasionOptionResult>>().Item2;
        MBTextManager.SetTextVariable("PERSUASION_REACTION", PersuasionHelper.GetDefaultPersuasionOptionReaction(optionResult), false);
        if (optionResult == PersuasionOptionResult.CriticalFailure)
          this._task.BlockAllOptions();
        return true;
      }

      private void guard_persuation_weapon_smuggling_selected_option_response_on_consequence()
      {
        Tuple<PersuasionOptionArgs, PersuasionOptionResult> tuple = ConversationManager.GetPersuasionChosenOptions().Last<Tuple<PersuasionOptionArgs, PersuasionOptionResult>>();
        float difficulty = Campaign.Current.Models.PersuasionModel.GetDifficulty(PersuasionDifficulty.VeryHard);
        float moveToNextStageChance;
        float blockRandomOptionChance;
        Campaign.Current.Models.PersuasionModel.GetEffectChances(tuple.Item1, out moveToNextStageChance, out blockRandomOptionChance, difficulty);
        this._task.ApplyEffects(moveToNextStageChance, blockRandomOptionChance);
      }

      private bool guard_persuation_weapon_smuggling_select_option_1_on_condition()
      {
        if (this._task.Options.Count <= 0)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(0), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(0).Line);
        MBTextManager.SetTextVariable("GUARDS_PERSUADE_ATTEMPT_1", text, false);
        return true;
      }

      private bool guard_persuation_weapon_smuggling_select_option_2_on_condition()
      {
        if (this._task.Options.Count <= 1)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(1), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(1).Line);
        MBTextManager.SetTextVariable("GUARDS_PERSUADE_ATTEMPT_2", text, false);
        return true;
      }

      private bool guard_persuation_weapon_smuggling_select_option_3_on_condition()
      {
        if (this._task.Options.Count <= 2)
          return false;
        TextObject text = new TextObject("{=bSo9hKwr}{PERSUASION_OPTION_LINE} {SUCCESS_CHANCE}");
        text.SetTextVariable("SUCCESS_CHANCE", PersuasionHelper.ShowSuccess(this._task.Options.ElementAt<PersuasionOptionArgs>(2), false));
        text.SetTextVariable("PERSUASION_OPTION_LINE", this._task.Options.ElementAt<PersuasionOptionArgs>(2).Line);
        MBTextManager.SetTextVariable("GUARDS_PERSUADE_ATTEMPT_3", text, false);
        return true;
      }

      private void guard_persuation_weapon_smuggling_select_option_1_on_consequence()
      {
        if (this._task.Options.Count <= 0)
          return;
        this._task.Options[0].BlockTheOption(true);
      }

      private void guard_persuation_weapon_smuggling_select_option_2_on_consequence()
      {
        if (this._task.Options.Count <= 1)
          return;
        this._task.Options[1].BlockTheOption(true);
      }

      private void guard_persuation_weapon_smuggling_select_option_3_on_consequence()
      {
        if (this._task.Options.Count <= 2)
          return;
        this._task.Options[2].BlockTheOption(true);
      }

      private PersuasionOptionArgs guard_persuation_weapon_smuggling_setup_option_1()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(0);
      }

      private PersuasionOptionArgs guard_persuation_weapon_smuggling_setup_option_2()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(1);
      }

      private PersuasionOptionArgs guard_persuation_weapon_smuggling_setup_option_3()
      {
        return this._task.Options.ElementAt<PersuasionOptionArgs>(2);
      }

      private bool guard_persuation_weapon_smuggling_clickable_option_1_on_condition(
        out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 0)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(0).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(0).IsBlocked;
      }

      private bool guard_persuation_weapon_smuggling_clickable_option_2_on_condition(
        out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 1)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(1).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(1).IsBlocked;
      }

      private bool guard_persuation_weapon_smuggling_clickable_option_3_on_condition(
        out TextObject hintText)
      {
        hintText = new TextObject("{=9ACJsI6S}Blocked");
        if (this._task.Options.Count <= 2)
          return false;
        hintText = this._task.Options.ElementAt<PersuasionOptionArgs>(2).IsBlocked ? hintText : TextObject.Empty;
        return !this._task.Options.ElementAt<PersuasionOptionArgs>(2).IsBlocked;
      }

      private bool DialogStartCondition()
      {
        return !this._playerDodgedGuards && this._guardsParty != null && CharacterObject.OneToOneConversationCharacter == ConversationHelper.GetConversationCharacterPartyLeader(this._guardsParty.Party);
      }

      private void StartFight()
      {
        int upgradeLevel = this.QuestGiver.CurrentSettlement.IsTown ? this.QuestGiver.CurrentSettlement.Town.GetWallLevel() : 1;
        this._highCrimeRatingWillBeApplied = true;
        if (this._guardsParty.CurrentSettlement == null)
          this._guardsParty.CurrentSettlement = this.QuestGiver.CurrentSettlement;
        PlayerEncounter.RestartPlayerEncounter(this._guardsParty.Party, PartyBase.MainParty, false);
        PlayerEncounter.StartBattle();
        GameMenu.ActivateGameMenu("town");
        int num = (int) (5.0 + 15.0 * (double) this._issueDifficulty);
        CampaignMission.OpenBattleMissionWhileEnteringSettlement(this.QuestGiver.CurrentSettlement.LocationComplex.GetLocationWithId("center").GetSceneName(upgradeLevel), upgradeLevel, num, num);
        this._checkForBattleResult = true;
      }

      private void PlayerDodgeGuardsLowCrimeRating()
      {
        this.PlayerDodgedGuards();
        this._lowCrimeRatingWillBeApplied = true;
      }

      private bool CheckPlayersPartySize()
      {
        return MobileParty.MainParty.MemberRoster.TotalRegulars - MobileParty.MainParty.MemberRoster.TotalWoundedRegulars > 30;
      }

      private void PlayerDodgedGuards()
      {
        MBInformationManager.AddQuickInformation(new TextObject("{=vYRbyXkz}The guards won't come after you anymore."));
        if (this._guardsParty.IsActive && this._guardsParty.IsVisible)
          DestroyPartyAction.Apply(PartyBase.MainParty, this._guardsParty);
        this._playerDodgedGuards = true;
      }

      private void PlayerBribeGuard()
      {
        GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, (Hero) null, this._bribeGold);
        this.PlayerDodgedGuards();
      }

      private void DeleteAllWeaponsFromPlayer()
      {
        Dictionary<EquipmentElement, int> dictionary = new Dictionary<EquipmentElement, int>();
        foreach (ItemRosterElement itemRosterElement in PartyBase.MainParty.ItemRoster)
        {
          EquipmentElement equipmentElement = itemRosterElement.EquipmentElement;
          if (equipmentElement.Item != null)
          {
            equipmentElement = itemRosterElement.EquipmentElement;
            if (!equipmentElement.IsQuestItem)
            {
              equipmentElement = itemRosterElement.EquipmentElement;
              if (equipmentElement.Item.WeaponComponent != null && itemRosterElement.Amount > 0 && !dictionary.ContainsKey(itemRosterElement.EquipmentElement))
              {
                dictionary.Add(itemRosterElement.EquipmentElement, itemRosterElement.Amount);
                PartyBase.MainParty.ItemRoster.AddToCounts(itemRosterElement.EquipmentElement, -itemRosterElement.Amount);
              }
            }
          }
        }
        this._weaponsThatGuardTook = dictionary;
        this.CalculateAndSetRequestedItemCountOnPlayer();
      }

      private void QuestSuccessDeleteWeaponsFromPlayer()
      {
        int requestedWeaponAmount = this._requestedWeaponAmount;
        for (int index = PartyBase.MainParty.ItemRoster.Count - 1; index >= 0; --index)
        {
          ItemRosterElement itemRosterElement = PartyBase.MainParty.ItemRoster[index];
          EquipmentElement equipmentElement = itemRosterElement.EquipmentElement;
          if (equipmentElement.Item != null)
          {
            equipmentElement = itemRosterElement.EquipmentElement;
            if (equipmentElement.Item.WeaponComponent != null)
            {
              equipmentElement = itemRosterElement.EquipmentElement;
              if (equipmentElement.Item.WeaponComponent.PrimaryWeapon.WeaponClass == this._requestedWeaponClass && itemRosterElement.Amount > 0)
              {
                if (requestedWeaponAmount >= itemRosterElement.Amount)
                {
                  PartyBase.MainParty.ItemRoster.AddToCounts(itemRosterElement.EquipmentElement, -itemRosterElement.Amount);
                  requestedWeaponAmount -= itemRosterElement.Amount;
                }
                else
                {
                  PartyBase.MainParty.ItemRoster.AddToCounts(itemRosterElement.EquipmentElement, -requestedWeaponAmount);
                  break;
                }
              }
            }
          }
          if (requestedWeaponAmount == 0)
            break;
        }
      }

      private bool HasPlayerEnoughMoneyToBribe(out TextObject hintText)
      {
        hintText = TextObject.Empty;
        if (Hero.MainHero.Gold >= this._bribeGold)
          return true;
        hintText = new TextObject("{=1V6DRayw}You don't have {BRIBE_COST} denars.");
        hintText.SetTextVariable("BRIBE_COST", this._bribeGold);
        return false;
      }

      private void PlayerDefeatedAgainstGuards()
      {
        this.AddLog(this.FailPlayerDefeatedAgainstGuardsLogText);
        this.QuestGiver.AddPower(-10f);
        this.RelationshipChangeWithQuestGiver = -5;
        this.CompleteQuestWithFail();
      }

      private void PlayerSuccessfullyDeliveredWeapons()
      {
        this.AddLog(this.SuccessQuestLogText);
        GainRenownAction.Apply(Hero.MainHero, 2f);
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, (int) this._rewardGold);
        this.QuestGiver.AddPower(10f);
        this.RelationshipChangeWithQuestGiver = 5;
        this.QuestSuccessDeleteWeaponsFromPlayer();
        this._weaponsThatGuardTook.Clear();
        this.QuestGiver.CurrentSettlement.Town.Security -= 30f;
        if (this._lowCrimeRatingWillBeApplied)
          ChangeCrimeRatingAction.Apply(this.QuestGiver.CurrentSettlement.MapFaction, 30f);
        if (this._highCrimeRatingWillBeApplied)
          ChangeCrimeRatingAction.Apply(this.QuestGiver.CurrentSettlement.MapFaction, 60f);
        this.CompleteQuestWithSuccess();
      }

      public override void OnFailed()
      {
        if (this._lowCrimeRatingWillBeApplied)
          ChangeCrimeRatingAction.Apply(this.QuestGiver.CurrentSettlement.MapFaction, 30f);
        if (!this._highCrimeRatingWillBeApplied)
          return;
        ChangeCrimeRatingAction.Apply(this.QuestGiver.CurrentSettlement.MapFaction, 60f);
      }

      protected override void OnFinalize()
      {
        if (this._guardsParty == null || !this._guardsParty.IsActive)
          return;
        DestroyPartyAction.Apply(PartyBase.MainParty, this._guardsParty);
      }

      protected override void OnTimedOut()
      {
        this.AddLog(this.FailQuestTimedOutLogText);
        this.QuestGiver.AddPower(-10f);
        this.RelationshipChangeWithQuestGiver = -5;
      }
    }

    public class GangLeaderNeedsWeaponsIssueTypeDefiner : SaveableTypeDefiner
    {
      public GangLeaderNeedsWeaponsIssueTypeDefiner()
        : base(3940000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssue), 1);
        this.AddClassDefinition(typeof (GangLeaderNeedsWeaponsIssueQuestBehavior.GangLeaderNeedsWeaponsIssueQuest), 2);
      }
    }
  }
}
